package com.agger.eurekaclientuserservice.listener;

import com.agger.eurekaclientuserservice.model.excelTemp.ArticleTemp;
import com.agger.eurekaclientuserservice.services.ArticleService;
import com.agger.eurekacommonapi.vo.ArticleVO;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import org.dozer.DozerBeanMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @classname: ArticleReadListener
 * @description: EasyExcel:Article文件读取监听
 * @author chenhx
 * @date 2020-07-21 10:12:12
 */
public class ArticleReadListener extends AnalysisEventListener<ArticleTemp> {
    Logger logger = LoggerFactory.getLogger(ArticleReadListener.class);

    private DozerBeanMapper dozerMapper = new DozerBeanMapper();             //类转换器

    private ArticleService service;
    private List<ArticleVO> raws = new ArrayList<>();


    public ArticleReadListener(ArticleService service){
        this.service = service;
    }

    /**
     * @Title: invoke
     * @Description: 读取每一行
     * @param 
     * @return void
     * @author chenhx
     * @date 2020-07-21 11:09:27
     */
    @Override
    public void invoke(ArticleTemp article, AnalysisContext analysisContext) {
        logger.info("开始读取文章:{}", JSON.toJSONString(article));
        // 使用类转换器将模板对象转换为DTO对象
        ArticleVO vo = dozerMapper.map(article, ArticleVO.class);
        raws.add(vo);
    }

    /**
     * @Title: doAfterAllAnalysed
     * @Description: 读取完成
     * @param
     * @return void
     * @author chenhx
     * @date 2020-07-21 11:09:48
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        logger.info("一共读取了{}篇文章，标题分别是:{}", raws.size(), raws.stream().map(ArticleVO::getTitle).collect(Collectors.toList()));
        service.insertArticles(raws);
    }

    /**
     * @Title: invokeHeadMap
     * @Description: 一行一行解析头
     * @param 
     * @return void
     * @author chenhx
     * @date 2020-07-21 14:24:24
     */
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        logger.info("解析到一条头数据:{}", JSON.toJSONString(headMap));
        super.invokeHeadMap(headMap, context);

    }
}
